package org.oos.lists;

import java.io.File;
import java.io.Serializable;
import java.util.AbstractList;
import java.util.List;
import java.util.Map;

import org.oos.OOS4Java;
import org.oos.atom.entries.MultimediaEntry;
import org.oos.dao.lists.impl.FullAccessDynamicList;
import org.oos.model.Multimedia;
import org.oos.model.Review;
import org.oos.util.Cache;

public class MultimediaList extends AbstractList<Multimedia> implements Serializable {

	private static final long serialVersionUID = 5812266239234073341L;
	private OOS4Java oos4Java;
	private List<MultimediaEntry> list;
	private Review review;
	private transient Map<MultimediaEntry, Multimedia> cache = new Cache<MultimediaEntry, Multimedia>();

	public MultimediaList(OOS4Java oos4Java, List<MultimediaEntry> list,
			Review review) {
		this.oos4Java = oos4Java;
		this.list = list;
		this.review = review;
	}

	@Override
	public Multimedia get(int location) {
		MultimediaEntry entry = list.get(location);
		Multimedia result;
		if (cache.containsKey(entry)) {
			result = cache.get(entry);
		} else {
			result = new Multimedia(oos4Java, list.get(location));
			result.setReview(review);
			cache.put(entry, result);
		}
		return result;
	}

	@Override
	public int size() {
		return list.size();
	}

	@SuppressWarnings("unchecked")
	public boolean add(File file, String description, String contentType) {
		if (!((FullAccessDynamicList) list).addMedia(file, contentType)) {
			return false;
		}
		
		if (description != null) {
			MultimediaEntry entry = list.get(0);
			entry.setDescription(description);
			return list.set(0, entry) != null;
		}
		
		return true;
	}

	public boolean add(File file, String contentType) {
		return add(file, null, contentType);
	}

	@Override
	public boolean add(Multimedia media) {
		return list.add((MultimediaEntry) media.getEntry());
	}

	@Override
	public Multimedia remove(int index) {
		MultimediaEntry entry = list.remove(index);
		return new Multimedia(oos4Java, entry);
	}

	@Override
	public Multimedia set(int index, Multimedia media) {
		MultimediaEntry entry = list.set(index, media.getEntry());
		return new Multimedia(oos4Java, entry);
	}

	@Override
	public boolean remove(Object o) {
		return list.remove(o);
	}

}
